package ycl.base.common.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import ycl.base.common.constants.HtmlConstant;
import ycl.base.common.constants.RedisConstant;
import ycl.base.common.models.res.login.LoginRes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * redis逻辑操作
 *
 * @author: YCL
 * @date: 2021-06-04 15:54:32
 */
@Component
@Slf4j
public class RedisOperationUtil {

	@Resource
	private StringRedisTemplate stringRedisTemplate;


	/**
	 * 从redis里查询登录用户
	 *
	 * @param request 请求头
	 * @return 登录用户信息
	 */
	public LoginRes getLoginUser(HttpServletRequest request) {
		return getLoginUser(request, true);
	}

	public LoginRes getLoginUser(HttpServletRequest request, boolean throwE) {
		String token = request.getHeader(HtmlConstant.TOKEN);
		String v = stringRedisTemplate.opsForValue().get(RedisConstant.USER_LOGIN + token);
		if (throwE)
			Assert.notBlank(v, "用户未登录");
		return JSONObject.parseObject(v, LoginRes.class);
	}


	/**
	 * 退出登录, 删除用户在redis里的信息
	 *
	 * @param request 请求头
	 */
	public void logout(HttpServletRequest request) {
		String token = request.getHeader(HtmlConstant.TOKEN);
		stringRedisTemplate.delete(RedisConstant.USER_LOGIN + token);
	}

	/**
	 * 记录登录失败次数信息, 达上限后限定时间内不可再登录
	 *
	 * @param title 登录头
	 */
	public void recordLoginFailMsg(String title) {
		String key = RedisConstant.USER_LOGIN_FAIL + title;
		String value = stringRedisTemplate.opsForValue().get(key);
		if (StrUtil.isBlank(value)) {
			stringRedisTemplate.opsForValue().set(key, "1", 5L, TimeUnit.MINUTES);
			return;
		}

		int count = Integer.parseInt(value) + 1;
		stringRedisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_LOCK + title, "0", 5L, TimeUnit.MINUTES);
		if (count == RedisConstant.LOGIN_FAIL_COUNT)
			throw new IllegalArgumentException("登录失败达上限, 锁住账户 5 分钟");
	}

	/**
	 * 登录前检查用户是否被锁住
	 *
	 * @param title 登录头
	 */
	public void userLoginIsLock(String title) {
		String v = stringRedisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_LOCK + title);
		Assert.isNull(v, "登录失败达上限, 5 分钟后重试");
	}


}
